package cc.mrbird.febs.system.controller;


import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.common.exception.FebsException;
import cc.mrbird.febs.common.service.OssService;
import cc.mrbird.febs.common.utils.SortUtil;
import cc.mrbird.febs.system.entity.Course;
import cc.mrbird.febs.system.entity.Experiment;
import cc.mrbird.febs.system.entity.ExperimentProject;
import cc.mrbird.febs.system.entity.User;
import cc.mrbird.febs.system.service.ICourseService;
import cc.mrbird.febs.system.service.IExperimentProjectService;
import cc.mrbird.febs.system.service.IExperimentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import cc.mrbird.febs.common.controller.BaseController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 实验项目表 前端控制器
 * </p>
 *
 * @author Macw
 * @since 2020-03-25
 */
@RestController
@RequestMapping("/experimentProject")
public class ExperimentProjectController extends BaseController {

    @Resource
    private IExperimentProjectService experimentProjectService;

    @Resource
    private ICourseService courseService;

    @Resource
    private OssService ossService;

    @GetMapping("list")
    @RequiresPermissions("experimentProject:view")
    public FebsResponse courseList(ExperimentProject experimentProject, QueryRequest request) {
        System.out.println("experimentProject------------"+experimentProject);
        Page<ExperimentProject> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtil.handlePageSort(request, page, "project_id", FebsConstant.ORDER_ASC, false);
        IPage<ExperimentProject> iPage = this.experimentProjectService.page(page, new QueryWrapper<ExperimentProject>().lambda()
                .like(StringUtils.isNotBlank(experimentProject.getProjectName()), ExperimentProject::getProjectName, experimentProject.getProjectName())
                .like(experimentProject.getState() != null,ExperimentProject::getState,experimentProject.getState()));
        Map<String, Object> dataTable = getDataTable(iPage);
        return new FebsResponse().success().data(dataTable);
    }

    @PostMapping("/add")
    @RequiresPermissions("experimentProject:add")
    @ControllerEndpoint(operation = "新增项目", exceptionMessage = "新增项目失败")
    public FebsResponse addExperiment(@Valid ExperimentProject experimentProject,@RequestParam("file") MultipartFile file) {
        if (file != null && file.getSize() > 0) {
            //获取上传文件的路径
            String basePath = "project";
            String url ="";
            try {
                //调用阿里云OSS的上传方法
                url = ossService.aliOSSUpload(file, basePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取文件大小
            long size = file.getSize();
            //转换文件大小格式
            String size1 = getSize(size);
            //将文件大小，和文件上传后返回的路径，入库
            experimentProject.setReportSize(size1);
            experimentProject.setReportUrl(url);
        }
        experimentProject.setCreateTime(LocalDateTime.now());
        if (StringUtils.isNotBlank(experimentProject.getCourseName())){
            experimentProject.setCourseId(courseService.getOne(new QueryWrapper<Course>().lambda().eq(Course::getCourseName,experimentProject.getCourseName())).getCourseId());
        }
        experimentProjectService.save(experimentProject);
        return new FebsResponse().success();
    }

    @RequestMapping("downloadFile")
    public void downloadFile(String objectName){
        ossService.downloadOss(objectName);
    }

    /**
     *  GuiYongkang
     *  2020/4/01 14:44pm
     *  修改
     * */
    @PostMapping("/update")
    @RequiresPermissions("experimentProject:update")
    @ControllerEndpoint(operation = "修改项目", exceptionMessage = "修改项目失败")
    public FebsResponse updateExperiment(@Valid ExperimentProject experimentProject) {
        System.out.println("--------------"+experimentProject);
        if (experimentProject.getProjectId() == null) {
            throw new FebsException("实验ID为空");
        }
        experimentProject.setUpdateTime(LocalDateTime.now());
        this.experimentProjectService.updateById(experimentProject);
        return new FebsResponse().success();
    }
    /**
     *  GuiYongkang
     *  2020/4/01 17:16pm
     *  删除实验项目
     * */
    @GetMapping("delete/{projectIds}")
    @RequiresPermissions("experimentProject:delete")
    @ControllerEndpoint(operation = "删除实验项目", exceptionMessage = "删除实验项目失败")
    public FebsResponse deleteCourses(@NotBlank(message = "{required}") @PathVariable String projectIds) {
        System.out.println("---------A-----------"+projectIds);
        String[] ids = projectIds.split(StringPool.COMMA);
        List<String> list = Arrays.asList(ids);
        list.forEach(s -> System.out.println("-------------"+s));
        experimentProjectService.removeByIds(list);
        return new FebsResponse().success();
    }
}
